//
//  RequestNetWork.m
//  QRMaster
//
//  Created by myApple on 15/11/9.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "RequestNetWork.h"
#import "AFNetworking.h"
#import "InternationalControl.h"

@implementation RequestNetWork

+(RequestNetWork *)sharedRequestNetWork
{
    static RequestNetWork * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == nil) {
            instance = [[super allocWithZone:NULL]init];
        }
    });
    return instance;
}


-(void)initWithPath:(NSString *)path params:(NSDictionary *)params block:(void (^)(id downLoadData,id error))resultBlock
{
    
        NSString *  currentLanagage = [InternationalControl userLanguage];
        if ([currentLanagage isEqualToString:@"zh-Hans-CN"]) {
            currentLanagage = @"zh_cn";
        }
        else if([currentLanagage isEqualToString:@"zh-Hant-HK"])
        {
            currentLanagage = @"zh_tw";
        }
        else if([currentLanagage isEqualToString:@"zh-Hant-TW"])
        {
            currentLanagage = @"zh_tw";
        }
        else if([currentLanagage isEqualToString:@"en"])
        {
            currentLanagage = @"en_us";
        }
    
        [params setValue:currentLanagage forKey:@"l"];
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 10;
//    DDLOG(path,nil);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (resultBlock) {
            resultBlock(obj,nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if ([error.userInfo objectForKey:ERRORINFO]) {
            id obj = [NSJSONSerialization JSONObjectWithData:[error.userInfo objectForKey:ERRORINFO] options:NSJSONReadingMutableContainers error:nil];
            if ([[obj objectForKey:@"status"]integerValue] == 288)
            {
                [self cancelRequest:manager];
                NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
                [postDict setValue:@"288" forKey:@"startUp"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"startUp" object:postDict];
                
                return;
  
            }
            if (resultBlock)
            {
                resultBlock(nil,obj);
            }
        }
        else if([error code] == -1009)
        {
            NSMutableDictionary * errorDict = [[NSMutableDictionary alloc]init];
            [errorDict setValue:NSLocalizedString(@"lostNetwork",nil)  forKey:@"info"];
            if (resultBlock)
            {
                resultBlock(nil,errorDict);
            }
        }
        else if([error code] == kCFURLErrorTimedOut)
        {
            NSMutableDictionary * errorDict = [[NSMutableDictionary alloc]init];
            [errorDict setValue:NSLocalizedString(@"timeOut",nil)forKey:@"info"];
            if (resultBlock)
            {
                resultBlock(nil,errorDict);
            }
        }
    }];
}

//检查网络
-(BOOL)checkNetWork:(AFHTTPRequestOperationManager *)manager
{
    NSOperationQueue * operationQueue = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                break;
        case AFNetworkReachabilityStatusNotReachable:
            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];
    [manager.reachabilityManager startMonitoring];
    return true;
}

//取消所有请求
-(void)cancelRequest:(AFHTTPRequestOperationManager *)manager
{
    [[manager operationQueue]cancelAllOperations];
}

@end
